package com.v5ba.server.util;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * HTTP访问工具类
 */
public final class HttpClientUtil {

    private static final String CHARSET = "UTF-8";
    private static int timeout = 5000;
    private static final int DEFAULT_SO_TIME_OUT = 5000;
    private static final int DEFAULT_CONNECT_TIME_OUT = 5000;

    public static HttpVO doPost(String url, Map<String, String> header, String body, Integer soTimeOut, Integer conTimeOut) {

        long bm = System.currentTimeMillis();

        // 构造HttpClient的实例
        HttpClient httpClient = new HttpClient();

        // 设置字符编码
        // httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
        // "UTF-8");

        // 创建POST方法的实例
        PostMethod method = new PostMethod(url);

        method.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        if (header != null && !header.isEmpty()) {
            for (String k : header.keySet()) {
                method.setRequestHeader(k, header.get(k));
            }
        }

        if (body != null) {
            method.setRequestBody(body);
        }

        // 使用系统提供的默认的恢复策略
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        // 设置Cookie 忽略：CookiePolicy.IGNORE_COOKIES
        // 兼容：CookiePolicy.BROWSER_COMPATIBILITY
        method.getParams().setParameter("http.protocol.cookie-policy", "ignoreCookies");

        if (soTimeOut != null) {
            httpClient.getParams().setSoTimeout(soTimeOut);
        } else {
            httpClient.getParams().setSoTimeout(DEFAULT_SO_TIME_OUT);
        }

        if (conTimeOut != null) {
            httpClient.getParams().setConnectionManagerTimeout(conTimeOut);
        } else {
            httpClient.getParams().setConnectionManagerTimeout(DEFAULT_CONNECT_TIME_OUT);
        }

        try {
            // 执行PostMethod
            int statusCode = httpClient.executeMethod(method);

            // 获取响应内容
            InputStream resStream = method.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(resStream));
            StringBuffer resBuffer = new StringBuffer();
            String resTemp = "";
            while ((resTemp = br.readLine()) != null) {
                resBuffer.append(resTemp);
            }
            String htmlCode = resBuffer.toString();

            return new HttpVO(statusCode, htmlCode);

        } catch (IOException e) {
            return null;
        } finally {
            method.releaseConnection();
        }
    }

    public static HttpVO doPost(String url, String body) {
        return doPost(url, null, body, null, null);
    }

    public static class HttpVO {

        private int status;
        private String data;

        public HttpVO() {
            super();
        }

        public HttpVO(int status, String data) {
            super();
            this.status = status;
            this.data = data;
        }

        public int getStatus() {
            return this.status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getData() {
            return this.data;
        }

        public void setData(String data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "HttpVO{" + "status=" + this.status + ", data='" + this.data + '\'' + '}';
        }
    }
}